<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import { nextTick, onMounted, onUnmounted, provide, ref } from 'vue'
import type { Socket } from 'socket.io-client'
import { io } from 'socket.io-client'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import type { Message, TimeMessages } from '@/types/room'
import { MsgType, OrderType } from '@/enum'
import { getConsultOrderDetail } from '@/services/consult'
import type { ConsultOrderItem, Image } from '@/types/consult'
import dayjs from 'dayjs'
import { showToast } from 'vant'

const route = useRoute()
const store = useUserStore()
const consult = ref<ConsultOrderItem>()
let socket: Socket

const list = ref<Message[]>([])

const time = ref(dayjs().format('YYYY-MM-DD hh:mm:ss'))

const initialMsg = ref(true)

const completeEva = (score: number) => {
  // 1.找到评价
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  // 2.如果结束了
  if (item) {
    item.msg.evaluateDoc = { score }
    item.msgType = MsgType.CardEva
  }
}

provide('consult', consult)
provide('completeEva', completeEva)

// 1.建立和关闭socket连接
// 1.1建立连接
onMounted(() => {
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })

  socket.on('connect', () => {
    // 建立连接成功
    console.log('connect')
  })

  socket.on('error', (event) => {
    // 错误异常消息
    console.log(event)
  })

  socket.on('disconnect', () => {
    // 已经断开连接
    console.log('disconnect')
  })
})
// 1.2关闭连接
onUnmounted(() => {
  socket.close()
})

// 2.获取聊天记录(默认消息)
onMounted(() => {
  socket.on('connect', () => {
    // 清空数据数组
    list.value = []

    socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
      // 2.1处理默认消息
      const arr: Message[] = []
      data.forEach((item, index) => {
        // -----------------------
        if (index === 0) time.value = item.createTime
        // -----------------------
        // 2.1.1创建一条时间消息
        arr.push({
          id: item.createTime,
          msgType: MsgType.Notify,
          createTime: item.createTime,
          msg: {
            content: item.createTime
          },
          noScroll: initialMsg.value === false
        })
        // 2.1.2添加其他消息
        item.items.forEach((m) => {
          arr.push({ noScroll: initialMsg.value === false, ...m })
        })
      })
      // 2.3把处理好的数据放入列表
      list.value.unshift(...arr)
      // ---------------------------------------
      // 关闭刷新中效果
      loading.value = false
      // 判断是否有数据？没有提示 没有聊天记录了
      if (!data.length) {
        return showToast('没有更早的聊天记录了~')
      }
      // 如果是初始化获取的聊天，需要滚动到最底部
      // 如果是第二，三...次获取消息,不需要滚动到底部
      if (initialMsg.value) {
        nextTick(() => {
          socket.emit('updateMsgStatus', arr[arr.length - 1].id)
          window.scrollTo({ left: 0, top: document.body.scrollHeight })
          initialMsg.value = false
        })
      }
    })
  })
})

// 3. 获取订单详情
onMounted(async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  console.log(res)

  consult.value = res.data

  // 订单状态发生变化处理
  socket.on('statusChange', async () => {
    const res = await getConsultOrderDetail(route.query.orderId as string)
    // console.log(res)
    consult.value = res.data
  })
})

// 3. 发送文字和图片
const sendText = (text: string) => {
  // 3.1 把文字包装成一条文字消息发给服务器
  // 发送信息需要  发送人  收消息人  消息类型  消息内容
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content: text
    }
  })
}

const sendImg = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture: img
    }
  })
}

onMounted(() => {
  socket.on('receiveChatMsg', async (msg) => {
    // console.log(res)
    // 1.1 把消息对象放入消息数组
    list.value.push(msg)

    // 1.2 让页面滚动到最底部
    await nextTick()
    socket.emit('updateMsgStatus', msg.id)
    window.scrollTo({ left: 0, top: document.body.scrollHeight })
  })
})

// 4.查询聊天记录
const loading = ref(false)
const onRefresh = () => {
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="医生问诊室" />
    <room-status :status="consult?.status" :countdown="consult?.countdown" />
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message :list="list" />
    </van-pull-refresh>
    <room-action
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="sendText"
      @send-img="sendImg"
    />
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
